<?php
/**
 * Created by PhpStorm.
 * User: chniccs
 * Date: 2019-08-28
 * Time: 16:36
 */

namespace app\admin\controller;


use app\helper\OssHelper;
use app\model\AdminFolder;
use app\model\AdminImgs;
use app\util\ReturnCode;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\Request;

class Imgs extends Base
{

    public function index()
    {

    }

    /**
     * 通过服务器中转上传阿里云oss
     * @return array|string
     *
     */
    public function uploadImg()
    {
        $fid = $this->request->param('fid');
        $from= $this->request->param('from');
        $result = OssHelper::uploadFile($this->getUserTid());
        if (!$result['done']) {
            return $this->buildFailed(ReturnCode::INVALID, '上传失败', $result);
        } else {
            $data = ['name' => $result['name'],'file_type' => $result['file_type'], 'file_name' => $result['file_name'], 'url' => $result['url'], 'fid' => $fid];
            $done = AdminImgs::create($this->addTid($data));
            if ($done) {
                $insertId = $done->getData('id');
                $result['id']=$insertId;
                if($from==='froala'){
                    return ['link'=>$result['url']];
                }else{
                    return $this->buildSuccess($result, '上传成功');
                }
            } else {
                $delResult = OssHelper::deleteOssFile($result['name'],$this->getUserTid());
                return $this->buildFailed(ReturnCode::INVALID, '上传失败', $delResult);
            }
        }
    }

    /**
     * 删除图片
     * @return array
     */
    public function delImg()
    {
        $id = $this->request->param('id');
        $where = ['id' => $id];
        $where = $this->addTid($where);
        $model = AdminImgs::get($where);
        if ($model) {
            $data = $model->getdata();
            $affected = $model->delete();
            if ($affected > 0) {
                $result = OssHelper::deleteOssFile($data['name'],$this->getUserTid());
                if ($result['done']) {
                    return $this->buildSuccess($result, '删除成功');
                } else {
                    return $this->buildFailed(ReturnCode::DELETE_FAILED, '删除失败', null);
                }
            } else {
                return $this->buildFailed(ReturnCode::DELETE_FAILED, '删除失败', null);
            }
        } else {
            return $this->buildFailed(ReturnCode::DELETE_FAILED, '删除失败', null);
        }
    }

    /**
     * 批量删除图片
     * @return array
     */
    public function delImgs()
    {
        $ids = $this->request->param('ids');
        $ids = json_decode($ids);
        $where = ['id' => $ids];
        $where = $this->addTid($where);
        $adminImgsModel = new AdminImgs();
        try {
            $result = $adminImgsModel->where($where)->whereIn('id', $ids)->select();
            $data = [];
            $keys = [];
            foreach ($result as $item) {
                $data[] = $item['id'];
                $keys[] = $item['name'];
            }
            Db::startTrans();
            $affected = AdminImgs::destroy($data);
            if ($affected > 0) {
                $result = OssHelper::deleteOssFiles($keys,$this->getUserTid());
                if ($result['done']) {
                    Db::commit();
                    return $this->buildSuccess($result, '删除成功');
                } else {
                   throw new Exception();
                }
            } else {
                throw new Exception();
            }
        } catch (\Exception $e) {
            Db::rollback();
        }
        return $this->buildFailed(ReturnCode::DELETE_FAILED, '删除失败', null);
    }

    /**
     * 获取图片列表
     * @return array
     */
    public function getImgs()
    {
        $fid = $this->request->param('fid');
        $fileTypeStr = $this->request->param('fileType');
        $from= $this->request->param('from');
        $where = [];

        if (isset($fid)) {
            $where['fid'] = $fid;
        }
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $obj = new AdminImgs();
        if(isset($fileTypeStr)){
            try{
                $fileTypes = json_decode($fileTypeStr);
                $where['file_type']=$fileTypes;
            }catch (\Exception $e){}
        }
        try {
            $listObj = $obj->order('create_time DESC')->where($this->addTid($where))->paginate($limit, false, ['page' => $start])->toArray();
        } catch (DbException $e) {
            return $this->buildFailed(ReturnCode::INVALID, '获取失败', null);
        }
        if($from==='froala'){
            return $listObj['data'];
        }else{
            return $this->buildSuccess([
                'list' => $listObj['data'],
                'count' => $listObj['total']
            ]);
        }
//        echo $obj->getLastSql();


    }


    /**
     * 获取文件夹列表
     * @return array
     */
    public function getFolders()
    {
//        debug('begin');

        $where = [];
        $where = $this->addTid($where);
        $folders = AdminFolder::all($where);
//        debug('end');
//        echo debug('begin','end').'s';
        return $this->buildSuccess($folders);
    }

    /**
     * 添加文件夹
     * @return array
     */
    public function addFolder()
    {
        $data = [];
        $name = $this->request->param('name');
        if (isset($name)) {
            $data['name'] = $name;
            $data = $this->addTid($data);
            $done = AdminFolder::create($data);
            if ($done) {
                $response = ['id' => $done->getData('id'), 'name' => $name];
                return $this->buildSuccess($response);
            }
        }
        return $this->buildFailed(ReturnCode::ADD_FAILED, '创建失败');
    }

    /**
     * 删除分类
     * @return array
     */
    public function delFolder()
    {
        $id = $this->request->param('id');
        $where = ['id' => $id];
        $where = $this->addTid($where);
        $model = AdminFolder::get($where);
        if ($model) {
            Db::startTrans();
            try {
                $affected = $model->delete();
                if ($affected > 0) {
                    $where = ['fid' => $id];
                    $where = $this->addTid($where);
                    //修改关联的图片
                    $adminImgsModel = new AdminImgs();
                    $adminImgsModel->save(['fid' => null], $where);
                } else {
                    throw new Exception();
                }
                Db::commit();
                return $this->buildSuccess(null, '删除成功');
            } catch (Exception $e) {
                Db::rollback();
                return $this->buildFailed(ReturnCode::DELETE_FAILED, '删除失败2', null);
            }
        } else {
            return $this->buildFailed(ReturnCode::DELETE_FAILED, '删除失败', null);
        }
    }

    /**
     * 修改分类名
     * @return array
     */
    public function renameFolder()
    {
        $id = $this->request->param('id');
        $name = $this->request->param('name');
        $where = ['id' => $id, 'name' => $name];
        $where = $this->addTid($where);
        $model = AdminFolder::update($where);
        if ($model) {
            return $this->buildSuccess(null, '修改成功');
        } else {
            return $this->buildFailed(ReturnCode::DELETE_FAILED, '删除失败', null);
        }
    }

    /**
     * 移动文件
     * @return array
     */
    public function move()
    {
        $ids = $this->request->param('ids');
        $fid = $this->request->param('fid');

        //修改关联的图片
        try {
            $ids = json_decode($ids);
            $where = [];
            $where = $this->addTid($where);
            $adminImgsModel = new AdminImgs();
            $result = $adminImgsModel->where($where)->whereIn('id', $ids)->select();
            //更新数据对象中的原始数据
            $data = [];
            foreach ($result as $item) {
                $data[] = ['id' => $item['id'], 'fid' => $fid];
            }
            $done = $adminImgsModel->saveAll($data);
            if ($done) {
                return $this->buildSuccess(null, '修改成功');
            } else {
                throw new Exception();
            }
        } catch (\Exception $e) {
            return $this->buildFailed(ReturnCode::UPDATE_FAILED, '更新失败', null);
        }
    }

}